JQUERY TEXT ()

Vignesh S



jQuery text ()

The text() method in jQuery is used to get or set the text content of selected elements.

Syntax 

  1. To get text: $(selector).text();
  2. To set text: $("selector").text("new text");
  3. To set text using function: $(selector).text(function(index,currentcontent));
Parameter details 
  • Content (Mandatory):Specifies the new text to be applied to the selected elements. Any special characters in this parameter will be automatically encoded.
  • Function (index, currentContent) (Optional):A callback function that defines the new text for each selected element.
  • index: The position of the current element in the selection.
  • currentContent: The existing text content of the current element.

Difference between jQuery text()  and jQuery html()

  • The jQuery text () method is used to set or return text content without HTML markup, while the html() method sets or returns the inner HTML, which includes both text and HTML markup.
  • The text() method works with both XML and HTML documents, whereas the html() method is specifically for HTML documents.
Example 
To get text ():
<!DOCTYPE html>
<html>
<body>
  <p id="example">Hello, <strong>World!</strong></p>
  <script>
var text = $("#example").text();
console.log(text); // Output: "Hello, World!"
  </script>
</body>
</html>

To set text ():
<!DOCTYPE html>
<html>
<body>
  <p id="example">Hello, <strong>World!</strong></p>
  <script>
$("#example").text("New Text Here");
// Now, the content of the paragraph becomes: "New Text Here"
  </script>
</body>
</html>



Tags
Our website uses cookies to enhance your experience. Learn More
Accept !

GocourseAI

close
send